package cn.bookcycle.paypage.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.bookcycle.paypage.constant.BusinessData;
import cn.bookcycle.paypage.constant.Symbol;
import cn.bookcycle.paypage.util.DataFormatConvert;
import cn.bookcycle.paypage.util.Request;

@Controller
public class RequestPay {
private static final Logger logger = LoggerFactory.getLogger(RequestPay.class);
	
	/**
	 * 去支付信息确认页面
	 * 
	 * @param requestBody
	 * @return
	 */
	@RequestMapping(value = {"paymsg"}, method = RequestMethod.GET)
	public String PayMsgPage(String requestBody, Model model) {
		logger.warn("requestBody------{}", requestBody);
		if (requestBody != null) {
			try {
				requestBody = URLDecoder.decode(requestBody, Symbol.UTF8);
			} catch (UnsupportedEncodingException e1) {
				logger.warn("对请求参数进行URL解码异常！！！！！");
			}
			logger.info("收到项扬的请求是：{}",requestBody);
			JSONObject jsonObject = null;
			int payType = 0;
			String body = null;
			String spbillCreateIp = null;
			String tradeNo = null;
			int totalFee = 0;
			String account = null;
			String notifyUrl = null;
			String userId = null;
			try {
				jsonObject = new JSONObject(requestBody);
				// 从请求中获取参数
//				payType = jsonObject.getInt(Symbol.PAY_TYPE);
				body = jsonObject.getString(Symbol.BODY);
//				spbillCreateIp = jsonObject.getString(Symbol.SPBILL_CREATE_IP);
				tradeNo = jsonObject.getString(Symbol.TRADE_NO);
				totalFee = jsonObject.getInt(Symbol.TOTAL_FEE);
//				account = jsonObject.getString(Symbol.ACCOUNT);
//				notifyUrl = BusinessData.DEFAULT_NOTIFY_URL;
				userId = jsonObject.getString(Symbol.USER_ID);
				logger.warn("用户ID------{}", userId);
			} catch (JSONException e) {
				logger.warn("请求支付前端页面，解析请求参数为JSONObject时，出现异常！！！！！");
			}
			model.addAttribute(Symbol.PAY_TYPE, BusinessData.DEFAULT_PAY_TYPE);
			model.addAttribute(Symbol.BODY, body);
			model.addAttribute(Symbol.SPBILL_CREATE_IP, BusinessData.DEFAULT_SPBILL_CREATE_IP);
			model.addAttribute(Symbol.TRADE_NO, tradeNo);
			model.addAttribute(Symbol.TOTAL_FEE, totalFee);
			model.addAttribute(Symbol.ACCOUNT, BusinessData.DEFAULT_ACCOUNT);
			model.addAttribute(Symbol.NOTIFY_URL, BusinessData.DEFAULT_NOTIFY_URL);
			// 添加用户ID
			model.addAttribute(Symbol.USER_ID, userId);
		}
		return "index";
	}
	
	
	/**
	 * 去获取二维码页面
	 * 
	 * @param requestBody
	 * @return
	 */
	@RequestMapping(value = "paycode", method = RequestMethod.POST)
	public String QRCodePage(@RequestBody (required=false) String requestBody, Model model, String userId) {
		logger.info("请求二维码页面时，收到userId:{}", userId);
		// 对接收到的数据进行URL解码
		try {
			requestBody = URLDecoder.decode(requestBody, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			logger.warn("URL解码失败！！！！！");
		}
		logger.info(requestBody);
		// 解析获取的请求参数为json格式
		String json = DataFormatConvert.requestStr2Json(requestBody);
		// 向支付微服务接口发送POST请求，并接收返回的参数
		String result = Request.sendPost(BusinessData.PAY_URL, json);
		// 从支付微服务返回的参数中，解析出status
		JSONObject jsonObject = null;
		try {
			jsonObject = new JSONObject(result);
		} catch (JSONException e) {
			// 防止后面出现空指针异常
			jsonObject = new JSONObject();
			logger.warn("解析支付微服务返回的参数为JSONObject发生异常！！！");
		}
		String status = null;
		try {
			status = jsonObject.getString(Symbol.STATUS);
		} catch (JSONException e) {
			logger.warn("从jsonObject获取status出现异常！！！！");
		}
		String codeUrl = "";
		String tradeNo = "";
		logger.info("status:{}", status);
		if (BusinessData.REQ_SUCCESS_CODE.equals(status)) {
			// 如果请求支付接口成功就再解析出code_url、tradeNO
			try {
				codeUrl = jsonObject.getString(Symbol.CODE_URL);
				tradeNo = jsonObject.getString(Symbol.TRADE_NO);
			} catch (JSONException e) {
				logger.warn("从jsonObject获取codeUrl出现异常！！！！");
			}
			logger.info("codeUrl:{}", codeUrl);
			// 把code_url、tradeNo传给前端
			model.addAttribute(Symbol.CODE_URL, codeUrl);
			model.addAttribute(Symbol.TRADE_NO, tradeNo);
			// 把userId也传到前端
			model.addAttribute(Symbol.USER_ID, userId);
		} else if (BusinessData.REQ_FAILED_CODE.equals(status)) {
			// 如果请求支付不成功
		} else if (BusinessData.REQ_PAID.equals(status)) {
			// 如果请求支付的订单号已经付过款
		} else if (BusinessData.REQ_UNPAID.equals(status)) {
			// 如果请求支付的订单好，已经生成过二维码，但用户尚未支付
		}
		return "qrcode";
	}
	
}
